using UnityEngine;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {

    internal class InspectorField_SequenceClipSlice : InspectorField<AGAFieldModel_SequenceClipSlice> {

        InspectorField_ClipLink clipField;
        FloatField offsetField;
        FloatField startField;
        FloatField lengthField;

        protected override void BuildUI() {
            clipField = new InspectorField_ClipLink();
            clipField.Init("clip", source.clip, ageContext, OnClipChanged);

            offsetField = new FloatField("offset");
            offsetField.value = source.offset;
            offsetField.RegisterValueChangedCallback(evt => OnChanged());

            startField = new FloatField("start");
            startField.value = source.start;
            startField.RegisterValueChangedCallback(evt => OnChanged());

            lengthField = new FloatField("length");
            lengthField.value = source.length;
            lengthField.RegisterValueChangedCallback(evt => OnChanged());
        }


        protected override void DrawUI() {
            Add(clipField);
            Add(offsetField);
            Add(startField);
            Add(lengthField);
        }
        private void OnClipChanged() {
            var newClip = clipField.GetClip();
            if (newClip != null) {
                lengthField.value = newClip.length;
            }
            OnChanged();
        }

        private void OnChanged() {
            offsetField.value = Mathf.Max(offsetField.value, 0);
            source.offset = offsetField.value;
            startField.value = Mathf.Max(startField.value, 0);
            source.start = startField.value;
            lengthField.value = Mathf.Max(lengthField.value, 0);
            source.length = lengthField.value;

            inspectorChangeCallback?.Invoke();
        }
    }

}
